package com.avaliacao.service;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.avaliacao.entity.Usuario;

@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

  @PersistenceContext
  private EntityManager entityManager;

  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    return findByUsername(username);
  }
  
  private Usuario findByUsername(String username) {
    try{
      return entityManager.createNamedQuery("Usuario.findByUsername", Usuario.class)
                          .setParameter("username", username)
                          .getSingleResult();
      
    }catch (NoResultException e) {
      throw new UsernameNotFoundException("Usuario nao encontrado");
    }
  }
}
